package com.company.loganalyzer.repository;

import com.company.loganalyzer.model.LogEntry;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 日志数据访问层
 * 
 * 基于Spring Data Elasticsearch的Repository接口
 * 对应Python版本的es_client.py功能
 */
@Repository
public interface LogRepository extends ElasticsearchRepository<LogEntry, String> {

    /**
     * 根据日志级别查询
     */
    Page<LogEntry> findByLevel(String level, Pageable pageable);

    /**
     * 根据服务名查询
     */
    Page<LogEntry> findByServiceName(String serviceName, Pageable pageable);

    /**
     * 根据traceId查询
     */
    List<LogEntry> findByTraceIdOrderByTimestampAsc(String traceId);

    /**
     * 根据时间范围查询
     */
    Page<LogEntry> findByTimestampBetween(LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);

    /**
     * 根据级别和时间范围查询
     */
    Page<LogEntry> findByLevelAndTimestampBetween(String level, LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);

    /**
     * 根据服务名和时间范围查询
     */
    Page<LogEntry> findByServiceNameAndTimestampBetween(String serviceName, LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);

    /**
     * 根据级别、服务名和时间范围查询
     */
    Page<LogEntry> findByLevelAndServiceNameAndTimestampBetween(String level, String serviceName, LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);

    /**
     * 全文搜索日志消息
     */
    @Query("{\"bool\":{\"must\":[{\"query_string\":{\"query\":\"?0\",\"fields\":[\"message\",\"exception\"]}},?1]}}")
    Page<LogEntry> searchByMessageContent(String query, String additionalFilters, Pageable pageable);

    /**
     * 搜索错误日志
     */
    @Query("{\"bool\":{\"must\":[{\"terms\":{\"level\":[\"ERROR\",\"FATAL\",\"CRITICAL\"]}},?0]}}")
    Page<LogEntry> findErrorLogs(String additionalFilters, Pageable pageable);

    /**
     * 统计各级别日志数量
     */
    @Query("{\"size\":0,\"aggs\":{\"level_stats\":{\"terms\":{\"field\":\"level\"}}}}")
    List<LogEntry> getLogLevelStatistics();

    /**
     * 统计各服务日志数量
     */
    @Query("{\"size\":0,\"aggs\":{\"service_stats\":{\"terms\":{\"field\":\"service_name\"}}}}")
    List<LogEntry> getServiceStatistics();
}